package com.study.base.netty;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @description: BioServer
 * @date: 2021/1/20 20:32
 * @author: hcm
 * @version: 1.0
 */
public class BioServer {
    public static void main(String[] args) throws IOException {
        //线程池机制

        /**
         * 思路：
         * 1.创建一个线程池
         * 2.如果有客户端连接，就创建一个线程与之通讯
         *
         */
        ExecutorService newCachedThreadPool = Executors.newCachedThreadPool();
        //创建serverSocket
        ServerSocket serverSocket = new ServerSocket(666);
        System.out.println("服务器已启动");
        while (true){
            //监听,等待客户端连接
            Socket socket = serverSocket.accept();
            System.out.println("连接到一个客户端");

            //创建一个线程，与之通讯
            newCachedThreadPool.execute(new Runnable() {
                @Override
                public void run() {
                    //可以和客户端通讯
handler(socket);
                }
            });
        }
    }

    /**
     * 编写一个handler方法，和客户端通讯
     */
    public static void handler(Socket socket){
        byte[] bytes = new byte[1024];
        //通过socket获取输入流
        try {
            //为了证明bio一个线程对应一个连接
            System.out.println("线程id------->"+Thread.currentThread().getId()+" 线程名------>"+Thread.currentThread().getName());
            InputStream inputStream = socket.getInputStream();
            //循环读取客户端发送的数据
            while (true){
                int read = inputStream.read(bytes);
                if(read!=-1){
                    //输出客户端发送的数据
                    System.out.println(new String(bytes,0,read));
                }else{
                    break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();

        }finally {
            System.out.println("关闭client连接");
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
